<?php

namespace App\Repositories;

use App\Console\Commands\MassMessage;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Models\PasswordCoupon;
use App\Models\User;
use \Exception;
use App\Exceptions\Interfaces\SmsSendErrorException;

use App\Interfaces\SmsService;
use App\Models\MessageCode;
use App\Services\Sms;
use App\Services\SendSms;
use App\Interfaces\ShortMessageService;

use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms as Send;
class DayuSmsRepository implements SmsService
{
    use DispatchesJobs;
    protected $sendSmsClient;
    protected $sendSms;
    protected $codeLiveTime=600;

    public function __construct()
    {


        $config = [
            'accessKeyId'    => config('alisms.accessKeyId'),
            'accessKeySecret' => config('alisms.accessKeySecret'),
        ];
        $this->sendSmsClient  = new Client($config);
        $this->sendSms= new Send;
    }

    /**
     * 发送注册验证码: 尊敬的用户，您的验证码是：#${数字,4-10位}#$，#${文本,4位}#$欢迎您的注册
     * @param $phone
     * @param $code
     * @return mixed
     */
    /*public function sendRegMsg($phone)
    {

        //生成随机短信字符串
        $str='1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        $code= substr($randStr,0,4);//substr(string,start,length);
        //发送注册验证码

        $result = $this->smsClient->sendMsg('fix2','181',$phone,'尊敬的用户，您的验证码是：'.$code.'，阿福易购欢迎您的注册。');

        if ($result->code==0){
            $sendtime = date('Y-m-d H:i:s',time());
            //$param['session_id'] = session_id();
            $param['send_time'] = $sendtime;
            $param['phone'] = $phone;
            $param['code'] = $code;

            $messageCode = MessageCode::create($param);
            return $messageCode->id;

        }else{

            throw SmsSendErrorException('短信发送失败');
            return ;
        }

    }*/
    public function sendRegMsg($phoneNumbers)
    {
        //生成随机短信字符串
        $str='1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        $code= substr($randStr,0,4);//substr(string,start,length);
        //发送注册验证码
        $this->sendSms->setPhoneNumbers($phoneNumbers);
        $this->sendSms->setSignName('注册验证');
        $this->sendSms->setTemplateCode('SMS_33500155');
        $this->sendSms->setTemplateParam(['code' => $code,'product'=>'阿福易购']);
        $this->sendSms->setOutId('demo');
        $result=$this->sendSmsClient->execute($this->sendSms);
        if ($result->Message=="OK"){

            $sendtime = date('Y-m-d H:i:s',time());
            $param['send_time'] = $sendtime;
            $param['phone'] = $phoneNumbers;
            $param['code'] = $code;

            $messageCode = MessageCode::create($param);

            return $messageCode->id;

        }else{
            throw new SmsSendErrorException('短信发送失败');
            return ;
        }//end if()
    }

    public function sendMassMsg($phone_content){
            try {
                foreach ($phone_content as $phone=>$content) {
                    $result = $this->dispatch((new MassMessage($phone,$content,$templateId='', $signature='')));
                    $password_status[$phone]=$result['status'];
                }
            }catch (SmsSendErrorException $ex ){
                throw new SmsSendErrorException($ex->getMessage());
            }
            return $password_status;
    }


    public function validateRegCode($message_code_id,$code){

        $messageCode = MessageCode::find($message_code_id);

        if ($messageCode){

            if ($code==$messageCode->code&&strtotime(date('Y-m-d H:i:s',time()))-strtotime($messageCode->send_time)<=$this->codeLiveTime){

                return true;
            }

        }else{

            return false;
        }


    }

    //获取用户手机号集合
    public function getPhoneByObject($object){
        $phone = array();
        $user = User::all();
        if($object==1){
            $user = User::where('last_login_time','>',date('Y-m-d H:i:s',strtotime('-3 month')))->get();
        }
        if($object==2){
            $user = User::where('email', '<>', '')->get();
        }
        foreach ($user as $k=>$v) {
            $phone[]=$v->phone;
        }
        return $phone;


    }



}